package com.atguigu.gmall.cart.filter;

import com.atguigu.gmall.cart.util.CartThreadLocalUtil;
import com.atguigu.gmall.cart.util.TokenUtil;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * projectName: gmall
 *
 * @author: 陈鹏
 * time: 2022/10/8 0:23 星期六
 * description: 购物车过滤器
 */
@Order(1)
@WebFilter(filterName = "cartFilter",urlPatterns = "/*")
public class CartFilter extends GenericFilter {

    /**
     * 自定义的过滤器逻辑
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //获取请求头中的令牌: jwt
        String token = request.getHeader("Authorization").replace("bearer ", "");
        //使用工具类解析
        Map<String, String> map = TokenUtil.dcodeToken(token);
        if(map != null){
            //获取用户名
            String username = map.get("username");
            //存储用户名--本地线程对象
            CartThreadLocalUtil.set(username);
            //放行
            filterChain.doFilter(servletRequest,servletResponse);
        }

    }
}
